package sensornetwork.sensor;

import java.util.concurrent.ArrayBlockingQueue;
import snifc.sensor.QueueIfc;
import snifc.PacketIfc;
import sensornetwork.Packet;
import java.util.Iterator;
import java.util.TreeSet;
import java.lang.InterruptedException;


public class Queue implements QueueIfc {
	
	private ArrayBlockingQueue queue;
	private int taille;

	public Queue (int taille){
		this.taille = taille;
		this.queue = new ArrayBlockingQueue (taille);
	}
		
	public void enQueue(PacketIfc p) {
      try {
        if(!(this.queue.offer(p))) {
          throw new Exception();
        }
      } catch (Exception e) {
        System.out.println("Le packet n'a pas pu etre ajoute -- Queue full --");
      }
		}
	
	public PacketIfc deQueue(){
		return ((PacketIfc)queue.poll());
	}
  
  public String toString(int id) {
    TreeSet ss=new TreeSet(this.queue); 
		StringBuffer sb=new StringBuffer("Sensor # ");
		sb.append(id);
		sb.append(" is store : ");
    int boucle = 0;
    for(Iterator it = ss.iterator(); it.hasNext(); sb.append("-")) {
      sb.append(((Packet)it.next()).getId());
      boucle++;
    }
    if (boucle == 0) {
      sb.append("is empty");
    }
		return sb.toString();
  }
}
